package pers.cz.chat.filter;

import io.netty.channel.Channel;
import pers.cz.chat.constants.Commands;
import pers.cz.chat.constants.JefClolorEnum;
import pers.cz.chat.utils.LogUtils;
import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.netty.config.NettyConfigItem;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;
import pers.cz.netty.util.ContextHolder;

import java.util.Scanner;

/**
 * @version 1.0
 * @description: 登录消息拦截器
 * @author: ChengZhi 0336
 * @create: 2025-01-06 18:11
 **/
public class LoginSendFilter implements FilterHandler<Message, Channel> {

	@Override
	public boolean approve(Message message, Channel obj, FilterHandlerContext<Message,Channel> handlerContext) {
		Object contentOriginal = message.getContent();
		if (contentOriginal instanceof String) {
			String content = (String) contentOriginal;
			if (content.trim().startsWith(Commands.LOGIN.getCommand())) {

				if (ContextHolder.getRequestContext().get("sourceUserName") != null && !ContextHolder.getRequestContext().get("sourceUserName").isEmpty()) {
					LogUtils.print(JefClolorEnum.GREEN, ContextHolder.getRequestContext().get("sourceUserName") + "已登录！");
					return true;
				}
				String userName = ScannerImpl.getInput("请输入用户名：");
				String passWord = ScannerImpl.getInput("请输入密码：");

				message.setIp(JefConfiguration.get(NettyConfigItem.NETTY_SERVER_IP));
				message.setPort(JefConfiguration.getInt(NettyConfigItem.NETTY_SERVER_PORT, 9999));
				message.setMsgType(MsgType.AUTH);
				message.addAttachment("username", userName);
				message.addAttachment("password", passWord);
			}
		}
		// 设置聊天对象，和当前用户名
		message.addAttachment("source", ContextHolder.getRequestContext().get("sourceUserName"));
		message.addAttachment("target", ContextHolder.getRequestContext().get("targetUserName"));

		return handlerContext.doFilter(message, obj);
	}
}
